import React, { useState, useMemo, useCallback, useRef } from 'react';
import { connect, withRouter } from 'umi';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Select,
  Input,
  notification,
  message,
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { tableUpdate, tableDel, tableAdd } from './setServers';
import styles from '@/assets/setting/BuildSet.less';

const { Option } = Select;

/* 反回英文名称 */
const rename = (faclist: { [key: string]: any }[], text: string) => {
  if (!faclist.length || !text) return;
  for (const item of faclist) {
    if (item['siteid'] === text) {
      return item['ename'];
      break;
    }
  }
};

/* 编辑框 */
const ModeEdit = (props: any) => {
  console.log('modal 中的props', props.modalData);
  const modalRef = useRef(null);
  const [modalForm] = Form.useForm();
  const { modalVisible, modalData, modalOnCancel, modalUpdata } = props;

  /* Form 事件 */
  const modalFinish = (val: any) => {
    console.log('modal finish', val);
  };
  const modalFinishFailed = (val: any) => {
    console.log('modal finish failed', val);
  };
  /* Modal 事件 */
  const modalHandleOk = useCallback(() => {
    modalForm
      .validateFields()
      .then((val: any) => {
        delete modalData['key'];
        const params = { ...modalData, ...val };
        console.log('Modal 事件成功 val 值', val, params);
        if (modalUpdata(params)) {
          modalForm.resetFields();
        }
      })
      .catch((info: any) => {
        console.log('Modal 事件 info 值', info);
      });
  }, []);

  return (
    <Modal
      title={modalData['type'] === 'ADD' ? modalData['title'] : '编辑'}
      forceRender={false}
      visible={modalVisible}
      maskClosable={false}
      onOk={modalHandleOk}
      onCancel={modalOnCancel}
    >
      <Form
        name="modalEdit"
        form={modalForm}
        ref={modalRef}
        labelCol={{ span: 4 }}
        onFinish={modalFinish}
        onFinishFailed={modalFinishFailed}
        autoComplete="off"
        initialValues={{
          ...modalData,
          // id: modalData['id'],
          // name: modalData['name'],
        }}
      >
        <Form.Item
          name="ename"
          label="区域"
          rules={
            modalData['type'] === 'ADD'
              ? [{ required: true, message: '请选择区域！' }]
              : []
          }
        >
          {modalData['type'] === 'ADD' ? (
            <Select>
              {modalData['facList'] &&
                modalData['facList'].map((fac: any) => {
                  return (
                    <Option key={fac['ename']} value={fac['siteid']}>
                      {fac['ename']}
                    </Option>
                  );
                })}
            </Select>
          ) : (
            <Input placeholder={modalData['ename']} disabled />
          )}
        </Form.Item>
        <Form.Item
          name="name"
          label="Name"
          rules={[{ required: true, message: '请填写名称！' }]}
        >
          <Input placeholder="请编辑名称" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

const BuildSetTable = (props: any) => {
  console.log('BuildSetTable props', props);
  // const tabSearchInp = useRef(null);
  const { history, location, match } = props;
  const { getTableListAll } = props;
  // 仓库数据
  const { dvaData } = props;

  const [modalVisible, setModalVisible] = useState(false);
  const [modalData, setModalData] = useState({});

  const editName = (data: any) => {
    // console.log('单击单行数据！！！', data);
    setModalData({
      ...data,
      ename: rename(dvaData['facListAll'], data['siteid']),
    });
    setModalVisible(true);
  };

  // 设置搜索
  interface FilterDropdown {
    setSelectedKeys: any;
    selectedKeys: any;
    confirm: any;
    clearFilters: any;
  }
  const getColumnSearchProps = (dataIndex: string) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }: FilterDropdown) => {
      // console.log( dataIndex, 1, setSelectedKeys, 2, selectedKeys, 3, confirm, 4, clearFilters, );
      return (
        <div className={styles['tableSearchWrapper']}>
          <Input
            // ref={(node) => {
            //   console.log(node, 'node ???????/');
            //   tabSearchInp['current'] = node
            // }}
            // ref={tabSearchInp}
            allowClear
            value={selectedKeys[0]}
            onChange={(e: any) => {
              setSelectedKeys(e.target.value ? [e.target.value] : []);
              if (!e.target.value) {
                confirm({ closeDropdown: false });
              }
            }}
            onPressEnter={() => {
              confirm({ closeDropdown: false });
            }}
            className={styles['tableSearchInp']}
          />
          <Space>
            <Button
              size="small"
              onClick={() => {
                confirm({ closeDropdown: false });
                clearFilters();
              }}
            >
              Reset
            </Button>
            <Button
              type="primary"
              size="small"
              icon={<SearchOutlined />}
              onClick={() => {
                confirm({ closeDropdown: false });
                console.log('搜索的数据', selectedKeys[0], dataIndex);
              }}
            >
              Filter
            </Button>
          </Space>
        </div>
      );
    },
    filterIcon: (filtered: any) => (
      <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value: string, record: any) => {
      // console.log('搜索过滤');
      return record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : '';
    },
    // onFilterDropdownVisibleChange: (visible: string) => {
    //   console.log('visible ???', visible, tabSearchInp);
    //   // if (visible && tabSearchInp) {
    //   //   if( tabSearchInp.current ){
    //   //     setTimeout(() => tabSearchInp.current.select(), 100);
    //   //   }
    //   // }
    // },
  });

  interface TableThed {
    title: string;
    dataIndex: string;
    key: string;
    [key: string]: any;
  }
  const tableThead: TableThed[] = [
    {
      title: '区域',
      dataIndex: 'siteid',
      key: 'siteid',
      render: (text: string) =>
        text ? rename(dvaData['facListAll'], text) : text,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      ...getColumnSearchProps('name'),
    },
    {
      title: '处理',
      key: 'setting',
      dataIndex: 'setting',
      width: 280,
      render: (text: any, record: any) => {
        return (
          <Space>
            <Button
              size="small"
              type="primary"
              onClick={() => editName(record)}
            >
              编辑
            </Button>
            <Button
              size="small"
              type="primary"
              danger
              onClick={() => {
                // console.log('删除数据', record);
                tableDel(record)
                  .then((res) => {
                    notification.success({
                      message: '删除结果！',
                      description: res.message || '删除成功！',
                    });
                    getTableListAll();
                  })
                  .catch((rej) => {
                    notification.error({
                      message: '删除结果！',
                      description: rej.message || '删除失败！',
                    });
                  });
              }}
            >
              删除
            </Button>
            <Button
              type="link"
              onClick={() => {
                record['ename'] = record['siteid']
                  ? rename(dvaData['facListAll'], record['siteid'])
                  : record['siteid'];
                if (record['id']) {
                  history.push(`/areaMtnSet/${record['id']}`, record);
                } else {
                  message.info('缺少ID！');
                }
              }}
            >
              编辑区域咨询
            </Button>
          </Space>
        );
      },
    },
  ];

  /* Modal 编辑 新增 */
  const modalUpdata = (val: any): boolean => {
    let success = true;
    if (val['type'] !== 'ADD') {
      tableUpdate(val)
        .then((res: any) => {
          // console.log('上传是否成功', res);
          notification.success({
            message: '数据更新',
            description: res.message || res.msg || '数据更新成功',
          });
          setModalVisible(false);
          getTableListAll();
        })
        .catch((rej) => {
          success = false;
          notification.error({
            message: '数据更新',
            description: rej.message || rej.msg || '数据更新失败',
          });
        });
    } else {
      const upParams = {
        siteid: val['ename'],
        name: val['name'],
      };
      tableAdd(upParams)
        .then((res: any) => {
          console.log('新增成功', res);
          notification.success({
            message: '数据新增',
            description: res.message || res.msg || '数据新增成功',
          });
          setModalVisible(false);
          getTableListAll();
        })
        .catch((rej: any) => {
          success = false;
          notification.error({
            message: '数据新增',
            description: rej.message || rej.msg || '数据新增失败',
          });
        });
    }
    return success;
  };
  const modalEdit = useMemo(() => {
    return (
      <ModeEdit
        key={modalVisible}
        modalVisible={modalVisible}
        modalOnCancel={() => {
          setModalVisible(false);
        }}
        modalUpdata={modalUpdata}
        modalData={modalData}
      />
    );
  }, [modalVisible, modalData]);

  return (
    <>
      {/* <Button
        onClick={() => {
          console.log(history, location, match, 'history, location, match');
          history.push('/areaMtnSet/5/D20211120', {show: true, title: "跳转！"})
        }}
      >
        跳转至建物区域资讯设定
      </Button> */}

      <Button
        onClick={() => {
          setModalData({
            type: 'ADD',
            title: '新增',
            facList: dvaData['facListAll'],
          });
          setModalVisible(true);
        }}
        className={styles['addData']}
      >
        新增
      </Button>

      <Table
        rowKey={(record: any): string => {
          return record['key'];
        }}
        className={styles['buildSetTab']}
        size="middle"
        columns={tableThead}
        dataSource={props['tableData']}
        pagination={false}
      />

      {modalEdit}
    </>
  );
};

/* 挂载 到仓库中 */
const mapStateToProps = (state: any) => {
  console.log('BuildSetTable mapStateToProps', state);
  return {
    // dvaData 属性名称 setting 指命名空间
    dvaData: state.setting,
  };
};
// 连接仓库
export default connect(mapStateToProps)(withRouter(BuildSetTable));
